<script setup>
import { ref, onMounted } from 'vue'
import { Map, View } from 'ol'
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import { Draw } from 'ol/interaction'
import { GeoJSON } from 'ol/format'
import 'ol/ol.css'

const mapRef = ref(null)
const map = ref(null)
const vectorSource = ref(null)
const vectorLayer = ref(null)
const drawInteraction = ref(null)
const isDrawing = ref(false)
const drawType = ref('Polygon')
const hasFeatures = ref(false)
const currentBaseMap = ref('vector') // 当前底图类型：vector(矢量), image(影像), terrain(地形)

// 开始绘制矢量图形
const startDrawing = () => {
  if (isDrawing.value) {
    // 如果已经在绘制，则停止当前绘制
    stopDrawing()
  }
  
  isDrawing.value = true
  
  // 创建矢量数据源
  vectorSource.value = new VectorSource()
  
  // 创建矢量图层
  vectorLayer.value = new VectorLayer({
    source: vectorSource.value
  })
  
  // 添加矢量图层到地图
  map.value.addLayer(vectorLayer.value)
  
  // 创建绘图交互
  drawInteraction.value = new Draw({
    source: vectorSource.value,
    type: drawType.value
  })
  
  // 添加绘图交互到地图
  map.value.addInteraction(drawInteraction.value)
  
  // 监听绘图结束事件
  drawInteraction.value.on('drawend', (event) => {
    console.log('绘图完成', event.feature)
    hasFeatures.value = true
    // 可以在这里添加其他逻辑，比如保存绘制的图形
  })
}

// 停止绘制
const stopDrawing = () => {
  if (drawInteraction.value) {
    map.value.removeInteraction(drawInteraction.value)
    drawInteraction.value = null
  }
  isDrawing.value = false
}

// 下载矢量图形
const downloadVector = () => {
  if (!vectorSource.value) {
    alert('请先绘制矢量图形')
    return
  }
  
  const features = vectorSource.value.getFeatures()
  if (features.length === 0) {
    alert('没有可下载的矢量图形')
    return
  }
  
  // 创建GeoJSON格式
  const format = new GeoJSON()
  const geoJsonStr = format.writeFeatures(features, {
    featureProjection: 'EPSG:4326',
    dataProjection: 'EPSG:4326'
  })
  
  // 创建下载链接
  const blob = new Blob([geoJsonStr], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = 'vector_data.geojson'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}

// 清除绘制的矢量图形
const clearDrawing = () => {
  if (vectorSource.value) {
    // 清除所有要素
    vectorSource.value.clear()
    hasFeatures.value = false
  }
  
  // 如果正在绘制，则停止绘制
  if (isDrawing.value) {
    stopDrawing()
  }
}

// 创建底图图层
const createBaseMapLayer = (type) => {
  let url
  switch (type) {
    case 'vector':
      url = 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
      break
    case 'image':
      url = 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=6&x={x}&y={y}&z={z}'
      break
    case 'terrain':
      url = 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=8&x={x}&y={y}&z={z}'
      break
    default:
      url = 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
  }
  
  return new TileLayer({
    source: new XYZ({
      url: url,
      crossOrigin: 'anonymous'
    })
  })
}

// 切换底图
const switchBaseMap = (type) => {
  if (!map.value || currentBaseMap.value === type) return
  
  // 移除当前底图
  const layers = map.value.getLayers()
  layers.forEach((layer, index) => {
    if (index === 0) { // 假设底图是第一个图层
      map.value.removeLayer(layer)
    }
  })
  
  // 添加新底图
  const newBaseMap = createBaseMapLayer(type)
  map.value.getLayers().insertAt(0, newBaseMap)
  
  // 更新当前底图类型
  currentBaseMap.value = type
}

onMounted(() => {
  // 初始化地图
  map.value = new Map({
    target: mapRef.value,
    layers: [
      new TileLayer({
        source: new XYZ({
          url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
          crossOrigin: 'anonymous'
        })
      })
    ],
    view: new View({
      center: [104, 35], // 地图中心坐标（经度，纬度）- 设置为中国中心
      zoom: 5,         // 初始缩放级别
      projection: 'EPSG:4326' // 使用WGS84坐标系
    })
  })
})
</script>

<template>
  <div class="map-container">
    <!-- <h1>OpenLayers + Vue 3 地图演示</h1> -->
    <div class="controls">
      <div class="button-group">
        <button 
          @click="switchBaseMap('vector')" 
          :class="{ active: currentBaseMap === 'vector' }"
          class="map-button"
        >
          矢量底图
        </button>
        <button 
          @click="switchBaseMap('image')" 
          :class="{ active: currentBaseMap === 'image' }"
          class="map-button"
        >
          影像底图
        </button>
        <button 
          @click="switchBaseMap('terrain')" 
          :class="{ active: currentBaseMap === 'terrain' }"
          class="map-button"
        >
          地形底图
        </button>
      </div>
      <div class="button-group">
        <button @click="startDrawing" :class="{ active: isDrawing }">
          {{ isDrawing ? '停止绘制' : '开始矢量化' }}
        </button>
        <button @click="clearDrawing" :disabled="!hasFeatures && !isDrawing">
          清除绘制
        </button>
        <button @click="downloadVector" :disabled="!hasFeatures">
          下载矢量图形
        </button>
      </div>
    </div>
    <div ref="mapRef" class="map"></div>
  </div>
</template>

<style scoped>
.map-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
}

h1 {
  margin: 20px 0;
  color: #333;
}

.controls {
  margin: 10px 0;
  display: flex;
  flex-direction: column;
  gap: 10px;
  width: 90%;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: center;
}

button {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}

button.active {
  background-color: #f44336;
}

button.active:hover {
  background-color: #d32f2f;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.map-button {
  background-color: #2196F3;
}

.map-button:hover {
  background-color: #0b7dda;
}

.map-button.active {
  background-color: #ff9800;
}

.map-button.active:hover {
  background-color: #e68900;
}

.map {
  width: 90%;
  height: 80vh;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>